<template lang="pug">
data-page(
  v-bind="pageParams"
)
  .registration-list
    .registration-list-table
      mt-table(
        v-bind="tableProps"
      )
    .registration-list-workflow
      .registration-list-workflow-top
        SectionTitle 工作流程
      .registration-list-workflow-table
        workflow(ref="Refworkflow")

  templatePreview(v-model="templatePreviewShow",:selectRows="selectRows",:action="templatePreviewAction",@handleQuery="handleQuery")
  pacsViewerDialog(v-model="pacsViewerDialogShow",:registrationIds="registrationIds",:deviceId="deviceId",@handleQuery="handleQuery")
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type Action,
  type TableProps,
  useNotify,
  SectionTitle,

} from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import { type QueryPagination, useApi } from "@scmt/core-api";
import {
  type RegistrationEntity,
  type RegistrationQueryParams,
  adviceColumns,
  ERegistrationColumnKey,
  RegistrationStateEnum,
  registrationStateColorMap,
} from "@scmt/api-pacs-registration";
import templatePreview from "../../../work-list/src/work/components/templatePreview.vue";
import pacsViewerDialog from "../../../work-list/src/work/components/pacs-viewer-dialog.vue";
import workflow from "../../../work-list/src/work/components/workflow.vue";
import { useUser } from "@scmt/common-store";

const user = useUser();
const Refworkflow = ref<InstanceType<typeof workflow>>();
const $api = useApi();
const $notify = useNotify();
const queryPramas = reactive<RegistrationQueryParams>({
  name: "",
  pageNum: 1,
  pageSize: 20,
  registrationState: RegistrationStateEnum.Reviewed + "," + RegistrationStateEnum.Printed,
});
const selectRows = ref<any[]>([]);
const editingObj = ref<null | RegistrationEntity>(null);
const templatePreviewShow = ref(false);
const templatePreviewAction = ref("print");

const pacsViewerDialogShow = ref(false);
const registrationIds = ref("");
const deviceId = ref("");

const RegistrationStateOptions = [
  { label: "已审核", value: RegistrationStateEnum.Reviewed },
  { label: "已打印", value: RegistrationStateEnum.Printed },
];

const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    const params = Object.assign({ executionOfficeId: user.currentOfficeId ?? "currentOfficeId" }, queryPramas, q);
    return $api.pacs.registration.query(params);
  },
  save: (model: RegistrationEntity) => {
    return $api.pacs.registration.save(model).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  batchUpdate: (models: any) => {
    return $api.pacs.registration.batchUpdate(models).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  destroy: (ids: string) => {
    return $api.pacs.registration.destroy(ids).then(() => {
      $notify.success("删除成功");

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  //患者类型字典
  patientType: () => $api.dict.item.listAsOptions("patient-type"),
});

onMounted(() => {
  request(["patientType", "tableData"]);
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "name",
      label: "患者姓名",
    },
    {
      prop: "inspectionNumber",
      label: "检查编号",
    },

    {
      prop: "patientType",
      label: "患者来源",
      as: "select",
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("patient-type"),
      },
    },
    {
      prop: "executionState",
      label: "检查状态",
      as: "select",
      options: {
        multiple: true,
        separator: ",",
        options: RegistrationStateOptions,
      },
    },
  ];

  const headerActions: Action[] = [];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    actions: headerActions,
    onQuery: () => request("tableData"),
    onAct: onPageActions,
    columns: 4,
    alignAction: "left",
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    pagerCount: 5,
    columns: [
      {
        label: "序号",
        width: "60px",
        type: "selection",
      },
      adviceColumns[ERegistrationColumnKey.RegistrationStateLable],
      adviceColumns[ERegistrationColumnKey.PatientType],
      adviceColumns[ERegistrationColumnKey.InspectionNumber],
      adviceColumns[ERegistrationColumnKey.AdmissionNumber],
      adviceColumns[ERegistrationColumnKey.Name],
      adviceColumns[ERegistrationColumnKey.Sex],
      adviceColumns[ERegistrationColumnKey.Age],
      adviceColumns[ERegistrationColumnKey.DeviceName],
      adviceColumns[ERegistrationColumnKey.ProjectName],
      adviceColumns[ERegistrationColumnKey.ApplyOfficeName],
      adviceColumns[ERegistrationColumnKey.RegistrationTime],
      {
        label: "操作",
        fixed: "right",
        width: "150px",
        actions: [
          { label: "打印", event: "print", type: "primary" },
          { label: "影像", event: "image", type: "primary" },
        ],
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    highlightCurrentRow: true,
    onRowClick: (row: any) => {
      if (Refworkflow.value) {
        Refworkflow.value.handleQuery(row);
      }
    },
    //@ts-ignore
    cellStyle: ({ row, column }) => {
      if (column.property === adviceColumns[ERegistrationColumnKey.RegistrationStateLable].prop) {
        return {
          //@ts-ignore
          backgroundColor: `${registrationStateColorMap[row[column.property]] || ""} !important`,
        }
      }
    },
  };
  return tableProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "add":
    case "edit":
      editingObj.value = $api.pacs.registration.$$createEntity(model);
      break;
    case "destroy":
      request("destroy", model ? model.id : "");
      break;
    case "image":
      let ids = "";
      selectRows.value = [model];
      selectRows.value.forEach((element) => {
        //@ts-ignore
        if (element && element.id) {
          if (ids) {
            ids += ",";
          }
          //@ts-ignore
          ids += element.id;
          //@ts-ignore
          deviceId.value = element.deviceId;
        }
      });
      pacsViewerDialogShow.value = true;
      registrationIds.value = ids;
      // window.open(
      //   "/#/pacs/workList/pacsViewer/viewer?registrationIds=" + ids,
      //   "_blank"
      // );
      break;
    case "report":
      selectRows.value = [model];
      templatePreviewShow.value = true;
      templatePreviewAction.value = "report";
      break;
    case "examine":
      selectRows.value = [model];
      templatePreviewAction.value = "examine";
      templatePreviewShow.value = true;
      break;
    case "print":
      selectRows.value = [model];
      templatePreviewAction.value = "print";
      templatePreviewShow.value = true;
      break;
  }
};

//重置查询
const handleQuery = (q: any) => {
  return request("tableData", q);
};

defineExpose({
  handleQuery,
});
//监听科室改变
watch(
  () => user.currentOfficeId,
  (item) => {
    if (item) {
      request("tableData", {});
    }
  },
  {
    immediate: true,
  }
);

</script>

<style lang="less" scoped>
.registration-list {
  display: flex;
  flex-direction: column;
  height: 100%;

  &-table {
    flex: 1;
  }

  &-workflow {
    flex-shrink: 0;
    margin-top: var(--mt-margin);
    height: calc(30% - 10px);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    border-top: 1px dashed #d9dce1;

    &-top {
      flex-shrink: 0;
    }

    &-table {
      height: calc(100% - 37px);
      flex: 1;
    }
  }
}
</style>
